package com.x.component.utils;

import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * @author Deson
 * @ClassName: AppOpUtils
 * @Description: APP操作工具类
 * @date 2018年11月7日 上午10:07:54
 */
public class AppOpUtils {

	public static boolean openApp(Context context, String pkg, String act) {
		try {
			Intent intent = new Intent();
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setClassName(pkg, act);
			context.startActivity(intent);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	public static boolean openAppByClassName(Context context, String action, String pkgName, String className) {
		try {
			if (TextUtils.isEmpty(pkgName) || TextUtils.isEmpty(className)) {
				return false;
			}
			Intent intent = new Intent();
			if (TextUtils.isEmpty(action)) {
				intent.setAction(action);
			}
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setPackage(pkgName);
			intent.setClassName(pkgName, className);
			context.startActivity(intent);
			return true;
		} catch (Exception e) {
			Log.d("drag", "open app fail maybe target app is not installed: " + e.getMessage());
		}
		return false;
	}

	public static boolean openAppByComponent(Context context, String action, String pkgName, String className) {
		try {
			if (TextUtils.isEmpty(pkgName) || TextUtils.isEmpty(className)) {
				return false;
			}
			Intent intent = new Intent();
			if (!TextUtils.isEmpty(action)) {
				intent.setAction(action);
			}
			ComponentName componentName = new ComponentName(pkgName, className);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setPackage(pkgName);
			intent.setComponent(componentName);
			context.startActivity(intent);
			return true;
		} catch (Exception e) {
			Log.d("drag", "open app fail maybe target app is not installed: " + e.getMessage());
		}
		return false;
	}

	public static boolean openSrcApp(Context context, String pkgName, String className) {
		try {
			if (TextUtils.isEmpty(pkgName) || TextUtils.isEmpty(className)) {
				return false;
			}
			Intent intent = new Intent();
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setPackage(pkgName);
			intent.setClassName(pkgName, className);
			context.startActivity(intent);
//            context.startActivityAsUser(intent,Usber);
			return true;
		} catch (Exception e) {
			Log.d("main", "open source  app fail maybe target app is not installed: " + e.getMessage());
		}
		return false;
	}

	/**
	 * 打开原车导航APP
	 *
	 * @param context
	 * @param pkgName
	 * @param className
	 * @param action
	 * @return
	 */
	public static boolean openOriginNaviApp(Context context, String pkgName, String className, String action) {
		try {
			if (TextUtils.isEmpty(pkgName) || TextUtils.isEmpty(className)) {
				return false;
			}
			Intent intent = new Intent();
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setPackage(pkgName);
			intent.setClassName(pkgName, className);
			if (!TextUtils.isEmpty(action)) {
				intent.setAction(action);
			}
			context.startActivity(intent);
			return true;
		} catch (Exception e) {
			Log.d("main", "open source  app fail maybe target app is not installed: " + e.getMessage());
		}
		return false;
	}

	public static boolean openTargetApp(Context context, String pkgName, String className) {
		try {

			if (TextUtils.isEmpty(pkgName) || TextUtils.isEmpty(className)) {
				return false;
			}
			Intent intent = new Intent();

			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setPackage(pkgName);
			intent.setClassName(pkgName, className);
			context.startActivity(intent);
			return true;
		} catch (Exception e) {
			Log.d("main", "open app fail maybe target app is not installed: " + e.getMessage());
		}
		return false;
	}

	/**
	 * @param context
	 * @param pkgName
	 * @param className carnetapp.bluetooth.activity.CarNetOSBluetoothActivity
	 * @return
	 */
	public static boolean isTopActivity(Context context, String pkgName, String className) {

//        Log.d("app", "pass:   " + className);
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(Integer.MAX_VALUE);
		String cmpNameTemp = null;
		String cmpClassName = null;
		if (null != runningTaskInfos) {
			cmpNameTemp = (runningTaskInfos.get(0).topActivity).getPackageName(); // 0代表是栈顶,1代表栈顶下面；每个应用有一个任务栈
			cmpClassName = (runningTaskInfos.get(0).topActivity).getClassName();
		}
		if (null == cmpNameTemp || null == cmpClassName) {
			return false;
		}
//        Log.d("app", "current pkgName: " + cmpNameTemp);
//        Log.d("app", "current className: " + cmpClassName);
		return (cmpNameTemp.equals(pkgName)) && (cmpClassName.equals(className));
	}

	public static boolean openAppByPkgName(Context context, String pkgName) {
//        Log.d("app", "open app by pkg name： " + pkgName);
		try {
			PackageManager pmManager = context.getPackageManager();
			String className = "";
			List<PackageInfo> installedApps = pmManager.getInstalledPackages(PackageManager.GET_ACTIVITIES);
			for (PackageInfo packageInfo : installedApps) {
				if (pkgName.equals(packageInfo.packageName)) {
					Intent intent3rd = pmManager.getLaunchIntentForPackage(packageInfo.packageName);
					if (intent3rd != null) {
						className = intent3rd.getComponent().getClassName();
					} else {
						continue;
					}
//                    ActivityInfo[] activities = packageInfo.activities;
//                    if (activities == null || activities.length == 0) {
//                        continue;
//                    }
//                    className = activities[0].name;

					break;
				}
			}
//            Log.d("app", "找到 class  name： " + className);
			openSrcApp(context, pkgName, className);

		} catch (Exception e) {
//            Log.d("app", "异常产生了 " + e.getMessage());
		}

		return true;
	}

	/**
	 * 获取当前栈顶
	 *
	 * @param context
	 * @return
	 */
	public static String[] getTopActivity(Context context) {

		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(Integer.MAX_VALUE);
		String cmpNameTemp = null;
		String cmpClassName = null;
		if (null != runningTaskInfos && runningTaskInfos.size() > 0) {
			cmpNameTemp = (runningTaskInfos.get(0).topActivity).getPackageName(); // 0代表是栈顶,1代表栈顶下面；每个应用有一个任务栈
			cmpClassName = (runningTaskInfos.get(0).topActivity).getClassName();
		}
		if (null == cmpNameTemp || null == cmpClassName) {
			return null;
		}
//        Log.d("app", "current pkgName: " + cmpNameTemp);
//        Log.d("app", "current className: " + cmpClassName);
		return new String[] { cmpNameTemp, cmpClassName };
	}

	public static void openVietnamVoiceRecognization(Context context) {
		try {
			Intent intent = new Intent();
			ActivityOptions options = ActivityOptions.makeBasic();
			options.setLaunchDisplayId(0);
			intent.setClassName("vn.autoai.android", "com.autoai.android.MainActivity");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent, options.toBundle());
		} catch (Exception e) {
		}
	}

	/**
	 * 获取进程号对应的进程名
	 *
	 * @param pid 进程号
	 * @return 进程名
	 */
	public static String getProcessName(int pid) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
			String processName = reader.readLine();
			if (!TextUtils.isEmpty(processName)) {
				processName = processName.trim();
			}
			return processName;
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException exception) {
				exception.printStackTrace();
			}
		}
		return null;
	}
}
